package zdream.control.foe.mm;

import java.util.ArrayList;
import java.util.List;

import zdream.control.world.MFoeBuff;
import zdream.control.world.MHookType;
import zdream.control.world.MHooks;
import zdream.control.world.Ticker;

/**
 * @author Zdream
 * @since 0.0.1
 * @date 2022-05-31
 */
public class MegaManWeaponModule extends MFoeBuff {
	public final MegaMan mm;
	public MegaManWeaponModule(MegaMan mm) {
		super(mm);
		this.mm = mm;
	}

	@Override
	public String getCategory() {
		return "weapon";
	}

	/* **********
	 * 武器道具 *
	 ********** */

	public final List<IMegaManWeapon> weapons = new ArrayList<>();
	public final List<IMegaManProp> props = new ArrayList<>();
	public int currentWeapon = 0;

	/**
	 * 在成功攻击的一步时间内, 为 true
	 */
	public boolean attacking;

	@Override
	public void init() {
		// weapons
		weapons.add(new BusterWeapon(mm)); // 第零位是白弹
//		Array<IMegaManProfileWeapon> profileWeapons = mm.profile.weapons;
//		for (int i = 0; i < profileWeapons.size; i++) {
//			this.weapons.add(profileWeapons.items[i].createWeapon(mm));
//		}

		// props
//		props = new Array<>(IMegaManProp.class);
//		Array<IMegaManProfileProp> profileProps = mm.profile.props;
//		for (int i = 0; i < profileProps.size; i++) {
//			this.props.add(profileProps.items[i].createProp(mm));
//		}
		props.add(new RushJetProp(mm));

		onHook(MHookType.TICK)
				.handle(this::tick)
				.buildAndSave();
	}

	public void tick(MHooks.MHookContext rawContext) {
		for (IMegaManWeapon weapon : weapons) {
			weapon.tick(mm, mm.world.ticker);
		}
	}

	public IMegaManWeapon getCurrentWeapon() {
		return weapons.get(currentWeapon);
	}

	void handleFire(Ticker ticker) {
		/*
		 * 以下情况可以攻击:
		 *
		 * 1. 当前配置武器时
		 * 2. 当前武器有能量时 (如果有能量限制);
		 * 3. 当前武器在蓄力完成、子弹个数等条件均满足时;
		 * 4. 洛克人不在受伤硬直状态
		 * 5. 洛克人不在滑铲状态 (注, 这里特殊, 是 slideDuration > 0 不让攻击)
		 *
		 * 如果武器能蓄力:
		 *
		 * 1. 当受伤硬直时, 蓄力消失 ?
		 * 2. 滑铲状态可以蓄力
		 */

		for (IMegaManWeapon weapon : weapons) {
			weapon.tick(mm, mm.world.ticker);
		}

		boolean attack = mm.controlModule.attack;
		boolean lastAttack = mm.controlModule.lastAttack;
		if (!lastAttack && attack) {
			IMegaManWeapon weapon = getCurrentWeapon();
			attacking = weapon.onAttackPressed(mm);
		} else if (lastAttack && !attack) {
			IMegaManWeapon weapon = getCurrentWeapon();
			attacking = weapon.onAttackReleased(mm);
		} else {
			attacking = false;
		}

		if (attacking && mm.motionModule.climbing >= MegaManMotionModule.CLIMBING) {
			mm.motionModule.climbHaltRemain = 250 - ticker.lDuration;
		}
	}

	/**
	 * <p>执行使用道具
	 * <p>道具使用限制就没有那么多, 硬直的情形下也能触发.
	 * 除非在过场或者 CG, 那确实不行.
	 * </p>
	 */
	void handleProp(Ticker ticker) {
		byte keyProp1 = mm.controlModule.keyProp1;
		if (keyProp1 == 1 && props.size() >= 1) {
			props.get(0).doUse();
		}
	}
}
